var createError = require('http-errors');
var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var formidable =require('formidable');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var openapiRounter= require('./src/controller/openapi');
console.log('环境变量值：'+process.env.NODE_ENV);
//add mongo connection
require('./src/util/mongodb');
var app = express();
var bodyParser = require('body-parser');
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));

// app.use(function(req,res,next){
//   console.log('Time: ', Date.now())
//   next();
// });
// app.use(function(req,res,next){
//   console.log('222');
//   next();
// });
function loginName(req,res,next){
  console.log('Request URL:', req.originalUrl);
  next();
}
function logMethod(req,res,next){
  console.log('Request URL:', req.method);
  next();
}
var loStuff = [loginName,logMethod]
app.use('/', indexRouter);
app.use('/users', usersRouter);
app.use("/api",openapiRounter);
// catch 404 and forward to error handler

app.use(function(req, res, next) {
  next(createError(404));
});
// error handler
app.use(function(err, req, res, next) {
  // set locals, only providing error in development
  res.locals.message = err.message;
  res.locals.error = req.app.get('env') === 'development' ? err : {};

  // render the error page
  res.status(err.status || 500);
  res.render('error');
});
process.on('exit', async (code) => {
  try { 
    await pool.end();
    if (code === 1000) {
      console.error('process:uncaughtException');
    }else if (code === 1001) {
       console.error('process:SIGINT');
    } else if (code === 1002) {
        console.error('process:SIGTERM');
    } else {
        console.error('process:unknown');
  }
  
  } catch (e) {}
});
process.on('uncaughtException',function(e){
  console.log(e);
  // 异常可以选择不退出
  process.exit(1000);
});
process.on('SIGINT',function () {
  process.exit(1001);
});
process.on('SIGTERM',function () {
  process.exit(1002);
});

module.exports = app;
